
---------------
-- Range Widget
---------------


local DebuffWatcher = CreateFrame("Frame")
local watcherIsActive = false
local nextUpdate = 0
local Events = {}

local DebuffArt = {
	Fire = "Interface\\Addons\\TidyPlates\\Widgets\\BossDebuffWidget\\Fire",
	Ice = "Interface\\Addons\\TidyPlates\\Widgets\\BossDebuffWidget\\Ice",
	Green = "Interface\\Addons\\TidyPlates\\Widgets\\BossDebuffWidget\\Green",
	Bomb = "Interface\\Addons\\TidyPlates\\Widgets\\BossDebuffWidget\\Bomb",
	Skulls = "Interface\\Addons\\TidyPlates\\Widgets\\BossDebuffWidget\\Skulls",
}

local DebuffsToWatch = {
	["Frost Beacon"] = "Ice",
}



local DebuffedUnits = {}

--DebuffedUnits["Boognish"] = true

local function ResetTable()
	wipe(DebuffedUnits)
	--DebuffedUnits["Boognish"] = true
end

function Events.UNIT_AURA(unitid)
	local unitname = UnitName(unitid)
	local requestUpdate = false
	-- Check Debuffs
	for index = 1, 40 do
		debuffName, _, _, _, debuffType = UnitDebuff(unitid,index)
		if not debuffName then break end
		if DebuffsToWatch[debuffName] then
			DebuffedUnits[unitname] = true
			requestUpdate = true
		end

	end
	
	if requestUpdate then TidyPlates:Update() end
end

function Events.PLAYER_ENTERING_WORLD()
	ResetTable()
	--for i, v in pairs(DebuffedUnits) do print(i, v) end
	-- Cycle through all units and update the table
end

function Events.PLAYER_REGEN_ENABLED()
	ResetTable()
	-- Clear the table
end

function Events.PLAYER_REGEN_DISABLED()

end

local function EventUpdate(frame, event, ...)
	if Events[event] then Events[event](...) end
end

local function PollUpdate()
	
end

-- Offset 10px vertical for centering on Neon
local function ActivateWatcher()
	if not watcherIsActive then 
		for event in pairs(Events) do DebuffWatcher:RegisterEvent(event) end
		DebuffWatcher:SetScript("OnEvent", EventUpdate) 
		--DebuffWatcher:SetScript("OnUpdate", PollUpdate) 
		watcherIsActive = true
	end
end

-- Use for prototype


local function UpdateBossDebuffWidget(self, unit)
	--print("Updating", unit.name)
	--if unit.name == "Boognish" then
	local DebuffType = DebuffedUnits[unit.name]
	if DebuffType then
		self.Texture:SetTexture(DebuffArt[DebuffType])
		self:Show()
	else 
		self:Hide()
	end		
end



local function CreateBossDebuffWidget(parent)
	ActivateWatcher()
	
	local frame = CreateFrame("Frame", nil, parent)
	frame:SetWidth(16); frame:SetHeight(16)
	-- Image
	frame.Texture = frame:CreateTexture(nil, "OVERLAY")
	frame.Texture:SetPoint("CENTER")
	frame.Texture:SetWidth(150)
	frame.Texture:SetHeight(150)
	-- Vars and Mech
	frame:Hide()
	frame.Update = UpdateBossDebuffWidget
	return frame
end

TidyPlatesWidgets.CreateBossDebuffWidget = CreateBossDebuffWidget